import 'package:flutter/material.dart';
import 'package:flutter_theme/colors.dart';
import 'package:flutter_theme/theme.dart';
import 'package:flutter_theme/theme_utils.dart';
import 'package:password_safety_keyboard/password_safety_keyboard.dart';
import 'package:route_manager/app_config.dart';
import 'package:flutter_lang/flutter_lang.dart';
import 'package:route_manager/wx_navigator.dart';
import '../models/wallet_info_model.dart';
import '../../module_config.dart';
import '../widgets/shake_animation_widget.dart';
import '../widgets/slide_transition_widget.dart';
import '../widgets/snack_headtips_widget.dart';
// import '../widgets/number_keyborad_widget.dart';
import '../widgets/solidpoint_password_widget.dart';
// import 'package:lifecycle_monitor/lifecycle_monitor.dart';

enum PINType {
  start,
  confirm,
}

class PINSettingPage extends StatefulWidget {
  // 恢复钱包来源
  final int walletSource;

  /// 默认设置功能，为true时为更改PIN码
  final bool isUpdate;

  PINSettingPage({Key key, this.walletSource = 0, this.isUpdate = false})
      : super(key: key);

  @override
  State<StatefulWidget> createState() => _PINSettingPageState();
}

class _PINSettingPageState extends State<PINSettingPage> {
  String tokenNumber = '';
  String confirmNumber = '';
  PINType pinType = PINType.start;
  bool _isSwitchAniShake = false;

  bool _isUpdate;

  @override
  void initState() {
    super.initState();
    _isUpdate = widget.isUpdate;
  }

  @override
  void dispose() {
    super.dispose();
  }

  Widget getTipsWidget() {
    List<Widget> widgetList = [];
    String descrip = _isUpdate
        ? '${WXLang.$t("authentication_inputNew_settingPin", package: ModuleConfig.moduleName)}'
        : '${WXLang.$t("authentication_setCodeTips_settingPin", package: ModuleConfig.moduleName)}';
    if (pinType != PINType.start) {
      descrip = _isUpdate
          ? '${WXLang.$t("authentication_confirmNew_settingPin", package: ModuleConfig.moduleName)}'
          : '${WXLang.$t("authentication_confirmCode_settingPin", package: ModuleConfig.moduleName)}';
    }
    if (_isUpdate) {
      widgetList.clear();
    } else {
      widgetList.add(Padding(
        padding: EdgeInsets.symmetric(vertical: 10),
        child: Text(
          pinType == PINType.start
              ? '${WXLang.$t("authentication_preTips_settingPin", package: ModuleConfig.moduleName)}'
              : '',
          textAlign: TextAlign.center,
          style: TextStyle(fontSize: 13),
        ),
      ));
      widgetList.add(Padding(
        padding: EdgeInsets.symmetric(vertical: 10),
        child: Text(
          pinType == PINType.start
              ? '${WXLang.$t("authentication_warningTips_settingPin", package: ModuleConfig.moduleName)}'
              : "",
          textAlign: TextAlign.center,
          style: TextStyle(fontSize: 13),
        ),
      ));
    }

    return Container(
      alignment: Alignment.center,
      padding: EdgeInsets.symmetric(vertical: 5),
      color: WXTheme.$c("authentication_scaffold_color"),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Padding(
            padding: EdgeInsets.symmetric(vertical: 10),
            child: Text(
              descrip,
              textAlign: TextAlign.center,
              style: TextStyle(
                  fontSize: 16, color: WXTheme.$c("authentication_common_text_title")),
            ),
          ),
        ]..addAll(widgetList),
      ),
    );
  }

  Widget getNumberKeyboradWidget() {
    return NumberKeyboradWidget(
      // isRandom: true,
      languageDelete:
          '${WXLang.$t("authentication_delete_keyboard", package: ModuleConfig.moduleName)}',
      backgroundColor: ThemeUtils.getThemeColor(
          context: context,
          brightnessColor: Colors.grey[400],
          darkColor: Colors.grey[600]),
      onTap: (value) {
        setState(() {
          if (pinType == PINType.start) {
            tokenNumber = value;
            _isSwitchAniShake = false;
          } else {
            confirmNumber = value;
          }
          if (value.length == 6) {
            /// 每次到6个元素的时候，切换状态
            if (pinType == PINType.start) {
              pinType = PINType.confirm;
            } else {
              pinType = PINType.start;
            }
          }

          if (tokenNumber.length == 6 && confirmNumber.length == 6) {
            if (tokenNumber == confirmNumber) {
              // 本地保存PIN备份
              WalletInfo().pinCode = confirmNumber;

              if (_isUpdate) {
                // 修改逻辑保存最新PinCode
                WalletInfo.savePinCodeName();
                WXNavigator.pop(context: context);
              } else {
                /// 注册息屏逻辑
                // StateObserver().registerObserver();

                switch (widget.walletSource) {
                  case 0:
                    WXNavigator().popAndPushNamed('/mnemonicBackup',
                        moduleName: ModuleConfig.moduleName, context: context);
                    break;
                  case 1:
                    WXNavigator().popAndPushNamed('/mnemonicRecover',
                        moduleName: ModuleConfig.moduleName, context: context);
                    break;
                  default:
                }
              }
            } else {
              /// 两次输入的内容不匹配逻辑添加
              SnackHeadTipsWidget.openSnackHeadTipsWidget(
                  AppConfig.navigatorKey.currentState.overlay.context,
                  '${WXLang.$t("authentication_diffCode_checkPin", package: ModuleConfig.moduleName)}');
              tokenNumber = '';
              confirmNumber = '';
              _isSwitchAniShake = true;
              pinType = PINType.start;
              _shakeAnimationController.start(shakeCount: 5);
            }
          } else {
            /// 请继续输入
          }

          print('onTap$value');
          print('tokenNumber$tokenNumber');
          print('confirmNumber$confirmNumber');
        });
      },
    );
  }

  /// 获取6个实心圆组件
  Widget getSolidpointPasswordWidget(BuildContext context, PINType pinpe) {
    return SolidpointPasswordWidget(
      inActiveColor: Colors.grey,
      activeColor: WXTheme.$c("authentication_transfer_stepper_inner_point_color"),
      key: ValueKey(pinType),
      password: pinType == PINType.start ? tokenNumber : confirmNumber,
    );
  }

  ShakeAnimationController _shakeAnimationController =
      ShakeAnimationController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: WXTheme.$c("authentication_header_background"),
        brightness: Brightness.dark,
        leading: IconButton(
            icon: Icon(
              Icons.arrow_back,
            ),
            onPressed: () {
              WXNavigator.pop(context: context);
            }),
        title: Text(_isUpdate
            ? '${WXLang.$t("authentication_updateCode_settingPin",
            package: ModuleConfig.moduleName)}'
            : '${WXLang.$t("authentication_setCode_settingPin",
            package: ModuleConfig.moduleName)}',
          style: TextStyle(fontSize: 18, color:WXTheme.$c("authentication_header_icon_text")),),
      ),
      body: Stack(
        children: <Widget>[
          Container(
            child: Column(
              children: <Widget>[
                getTipsWidget(),
                AnimatedSwitcher(
                  duration: Duration(milliseconds: 300),
                  transitionBuilder: (child, animation) {
                    if (_isSwitchAniShake) {
                      return ShakeAnimationWidget(
                        child: child,
                        isForward: true,
                        shakeCount: 5,
                        shakeRange: 0.2,
                        shakeAnimationController: _shakeAnimationController,
                      );
                    } else {
                      return SlideTransitionWidget(
                          child: child,
                          direction: AxisDirection.left,
                          position: animation);
                    }
                  },
                  child: getSolidpointPasswordWidget(context, pinType),
                ),
              ],
            ),
          ),
          Positioned(
            bottom: 0,
            child: getNumberKeyboradWidget(),
          )
        ],
      ),
    );
  }
}
